package com.ren.frame;

import com.ren.constants.AppConstants;
import org.fife.ui.rsyntaxtextarea.*;

import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

/**
 * Markdown编辑器面板
 * 基于RSyntaxTextArea实现，提供Markdown语法高亮和编辑功能
 */
public class MarkdownEditorPane extends RSyntaxTextArea {

    private String category;
    private MarkdownPreviewPanel previewPanel;

    public MarkdownEditorPane(String category) {
        this.category = category;
        initializeEditor();
    }

    /**
     * 更新预览面板内容
     */
    private void updatePreview() {
        if (previewPanel != null) {
            previewPanel.setMarkdownContent(getText());
        }
    }

    /**
     * 初始化编辑器
     */
    private void initializeEditor() {
        // 设置语法高亮模式为Markdown
        setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_MARKDOWN);

        // 启用代码折叠
        setCodeFoldingEnabled(true);

        // 设置基本属性
        setFont(new java.awt.Font(AppConstants.FONT_NAME, java.awt.Font.PLAIN, AppConstants.FONT_SIZE));
        setEditable(false);
        setBackground(java.awt.Color.WHITE);

        // 启用基本换行
        setLineWrap(true);

        // 按单词边界换行
        setWrapStyleWord(true);

        // 初始化为有序列表模式
        initializeOrderedList();

        // 添加键盘监听器
        addKeyboardShortcuts();
    }

    /**
     * 初始化为有序列表模式
     */
    private void initializeOrderedList() {
        setText("1. ");
        setCaretPosition(getText().length());
    }

    /**
     * 添加键盘快捷键支持
     */
    private void addKeyboardShortcuts() {
        addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                // 处理回车键，自动生成新的列表项
                if (e.getKeyCode() == KeyEvent.VK_ENTER && !e.isShiftDown()) {
                    handleEnterKey();
                    e.consume();
                }
                // F2 标记为已完成（添加删除线）
                else if (e.getKeyCode() == KeyEvent.VK_F2) {
                    toggleCompleted();
                    e.consume();
                }
                // Ctrl + B 加粗
                else if (e.getKeyCode() == KeyEvent.VK_B && e.isControlDown()) {
                    applyBoldFormatting();
                    e.consume();
                }
                // Ctrl + I 斜体
                else if (e.getKeyCode() == KeyEvent.VK_I && e.isControlDown()) {
                    applyItalicFormatting();
                    e.consume();
                }
            }
        });
    }

    /**
     * 处理回车键事件
     */
    private void handleEnterKey() {
        if (!isEditable()) return;

        try {
            int caretPos = getCaretPosition();
            String text = getText();

            // 查找当前行
            int lineStart = 0;
            for (int i = caretPos - 1; i >= 0; i--) {
                if (text.charAt(i) == '\n') {
                    lineStart = i + 1;
                    break;
                }
            }

            // 获取当前行内容
            String currentLine = text.substring(lineStart, caretPos);

            // 如果当前行是列表项格式
            if (currentLine.matches("\\d+\\.\\s.*")) {
                // 重新计算当前行的正确序号
                int currentLineNumber = 1;
                String[] lines = text.substring(0, lineStart).split("\n");
                for (String line : lines) {
                    if (line.matches("\\d+\\.\\s.*")) {
                        currentLineNumber++;
                    }
                }

                // 插入新的列表项，序号为当前行序号+1
                String newListItem = "\n" + (currentLineNumber + 1) + ". ";
                insert(newListItem, caretPos);

                // 将光标移动到新列表项的末尾
                setCaretPosition(caretPos + newListItem.length());

                // 重新排列后续所有列表项的序号
                renumberListItems(caretPos + newListItem.length());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void setPreviewPanel(MarkdownPreviewPanel previewPanel) {
        this.previewPanel = previewPanel;
        // 添加文档监听器
        getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void changedUpdate(DocumentEvent e) {
                updatePreview();
            }

            @Override
            public void insertUpdate(DocumentEvent e) {
                updatePreview();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                updatePreview();
            }
        });
    }



    /**
     * 切换完成状态（添加/移除删除线）
     */
    private void toggleCompleted() {
        String selectedText = getSelectedText();
        if (selectedText != null && !selectedText.isEmpty()) {
            try {
                int start = getSelectionStart();
                int end = getSelectionEnd();

                // 检查是否已经标记为完成（以删除线形式）
                String currentText = getText();
                boolean isCompleted = false;

                if (start >= 2 && end <= currentText.length() - 2) {
                    String before = currentText.substring(start - 2, start);
                    String after = currentText.substring(end, end + 2);
                    if ("~~".equals(before) && "~~".equals(after)) {
                        isCompleted = true;
                    }
                }

                if (isCompleted) {
                    // 移除删除线标记
                    String newText = selectedText;
                    replaceRange(newText, start - 2, end + 2);
                    setSelectionStart(start - 2);
                    setSelectionEnd(start - 2 + newText.length());
                } else {
                    // 添加删除线标记
                    String newText = "~~" + selectedText + "~~";
                    replaceRange(newText, start, end);
                    setSelectionStart(start);
                    setSelectionEnd(start + newText.length());
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }


    /**
     * 获取分类标识
     */
    public String getCategory() {
        return category;
    }

    /**
     * 应用加粗格式
     */
    private void applyBoldFormatting() {
        String selectedText = getSelectedText();
        if (selectedText != null && !selectedText.isEmpty()) {
            try {
                int start = getSelectionStart();
                int end = getSelectionEnd();

                // 检查是否已经加粗
                String currentText = getText();
                boolean isBold = false;

                if (start >= 2 && end <= currentText.length() - 2) {
                    String before = currentText.substring(start - 2, start);
                    String after = currentText.substring(end, end + 2);
                    if ("**".equals(before) && "**".equals(after)) {
                        isBold = true;
                    }
                }

                if (isBold) {
                    // 移除加粗标记
                    String newText = selectedText;
                    replaceRange(newText, start - 2, end + 2);
                    setSelectionStart(start - 2);
                    setSelectionEnd(start - 2 + newText.length());
                } else {
                    // 添加加粗标记
                    String newText = "**" + selectedText + "**";
                    replaceRange(newText, start, end);
                    setSelectionStart(start);
                    setSelectionEnd(start + newText.length());
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * 应用斜体格式
     */
    private void applyItalicFormatting() {
        String selectedText = getSelectedText();
        if (selectedText != null && !selectedText.isEmpty()) {
            try {
                int start = getSelectionStart();
                int end = getSelectionEnd();

                // 检查是否已经斜体
                String currentText = getText();
                boolean isItalic = false;

                if (start >= 1 && end <= currentText.length() - 1) {
                    String before = currentText.substring(start - 1, start);
                    String after = currentText.substring(end, end + 1);
                    if ("*".equals(before) && "*".equals(after)) {
                        isItalic = true;
                    }
                }

                if (isItalic) {
                    // 移除斜体标记
                    String newText = selectedText;
                    replaceRange(newText, start - 1, end + 1);
                    setSelectionStart(start - 1);
                    setSelectionEnd(start - 1 + newText.length());
                } else {
                    // 添加斜体标记
                    String newText = "*" + selectedText + "*";
                    replaceRange(newText, start, end);
                    setSelectionStart(start);
                    setSelectionEnd(start + newText.length());
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * 重新排列列表项序号
     * @param fromPos 从哪个位置开始重新编号
     */
    private void renumberListItems(int fromPos) {
        try {
            String text = getText();
            String[] lines = text.split("\n");

            int lineNumber = 0;
            StringBuilder newText = new StringBuilder();
            int pos = 0;

            for (int i = 0; i < lines.length; i++) {
                String line = lines[i];
                if (line.matches("\\d+\\.\\s.*")) {
                    lineNumber++;
                    String content = line.substring(line.indexOf(". ") + 2);
                    String newLine = lineNumber + ". " + content;
                    newText.append(newLine);
                } else {
                    newText.append(line);
                }

                if (i < lines.length - 1) {
                    newText.append("\n");
                }
            }

            // 如果文本发生了变化，则更新文本
            if (!text.equals(newText.toString())) {
                int caretPos = getCaretPosition();
                setText(newText.toString());
                // 恢复光标位置
                if (caretPos <= newText.length()) {
                    setCaretPosition(caretPos);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
